import pygame

import os

import json

DATA_DIR = os.path.relpath(os.path.join(__file__,'..','..','data'))

def load_image(img_path):
  img_path = os.path.join(DATA_DIR,'media','images',img_path+'.png')
  
  return pygame.image.load(img_path)


def load_player_images(name):
  base_dir = os.path.join('player',name.lower())
  
  images = {}
  
  for form in ('Kit','Normal'):
    images[form] = {}
    
    form_imgs = images[form]
    
    work_dir = os.path.join(base_dir,form.lower())
    
    for static_pose in ('Idle','Fall','Jump'):
      form_imgs[static_pose] = load_image(os.path.join(work_dir,static_pose+'-0'))
    
    form_imgs['Run']  = []
    form_imgs['Walk'] = []
    
    for frame in range(8):
      img_name = os.path.join(work_dir,'Foo-'+str(frame))
      
      form_imgs['Run'].append( load_image(img_name.replace('Foo','Run')))
      form_imgs['Walk'].append(load_image(img_name.replace('Foo','Walk')))
    
  
  return images


def load_terrain_tile(tileset,group,name):
  base_path = os.path.join('terrain',tileset.lower(),group.lower())
  
  images = []
  
  for variant in 'ABCDEF':
    img_path = os.path.join(base_path,(name+'-'+variant))
    
    images.append(load_image(img_path))
  
  return images


def load_terrain_images(tileset):
  images = {}
  
  images['Solid'] = {}
  
  centered_pieces = ('Center','Top','Bottom')
  
  side_pieces     = ['Side','Top-Inside-Corner','Bottom-Inside-Corner',
                          'Top-Outside-Corner','Bottom-Outside-Corner']
  
  for name in centered_pieces:
    images['Solid'][name] = load_terrain_tile(tileset,'Solid',name)
  
  for name in side_pieces:
    base_imgs = load_terrain_tile(tileset,'Solid',name)
    
    images['Solid'][ 'Left-'+name] = base_imgs
    images['Solid']['Right-'+name] = [pygame.transform.flip(img,True,False) for img in base_imgs]
  
  return images


def load_level_file(name):
  file_path = os.path.join(DATA_DIR,'level',str(name)+'.lvl')
  
  lvl_file = open(file_path,'r')
  
  level_data = json.load(lvl_file)
  
  lvl_file.close()
  
  return level_data
